<template>
  <t-form
    ref="form"
    :data="formData"
    :rules="rules"
    :label-width="100"
    @submit="onSubmit"
  >
    <t-row :gutter="[16, 16]">
            <t-col :span="12">
        <t-form-item name="orderNumber" label="订单编号">
          <t-input
            v-model="formData.orderNumber"
            placeholder="请输入订单编号"
            clearable
          />
        </t-form-item>
      </t-col>
      <t-col :span="12">
        <t-form-item name="userId" label="用户ID">
          <t-input
            v-model="formData.userId"
            placeholder="请选择用户ID"
            clearable
          >

          </t-input>
        </t-form-item>
      </t-col>
    </t-row>

    <div class="operation-container">
      <t-space>
        <t-button theme="primary" type="submit">确定</t-button>
        <t-button theme="default" @click="onCancel">取消</t-button>
      </t-space>
    </div>
  </t-form>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { MessagePlugin, FormRule, SubmitContext } from 'tdesign-vue-next';
import { createOrder, updateOrder } from '@/api/product-orders';
import type { OrderInfo } from '@/api/product-orders';

const props = defineProps<{
  type: 'add' | 'edit';
  formData?: Partial<OrderInfo>;
}>();

const emit = defineEmits(['success', 'cancel']);

const form = ref();
const formData = ref<Partial<OrderInfo>>({});

// 表单验证规则
const rules = {
  orderNumber: [{ required: true, message: '请输入订单编号', trigger: 'blur' }],
  userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
} as Record<string, FormRule[]>;

watch(
  () => props.formData,
  (val) => {
    if (val) {
      formData.value = { ...val };
    }
  },
  { immediate: true }
);

// 表单提交
const onSubmit = async (ctx: SubmitContext) => {
  if (ctx.validateResult === true) {
    try {
      if (props.type === 'add') {
        await createOrder(formData.value as OrderInfo);
        MessagePlugin.success('新增成功');
      } else {
        if (!props.formData?.id) {
          MessagePlugin.error('缺少ID');
          return;
        }
        const updateData = {
          id: props.formData.id,
          ...formData.value
        };
        await updateOrder(updateData);
        MessagePlugin.success('更新成功');
      }
      emit('success');
    } catch (error) {
      console.error('提交失败:', error);
      MessagePlugin.error('提交失败');
    }
  }
};

// 取消处理
const onCancel = () => {
  emit('cancel');
};
</script>

<style lang="less" scoped>
.operation-container {
  margin-top: 20px;
  text-align: right;
}
</style> 